<template>
  <div :class="prefixCls">
    <div ref="editor" class="editor-wrapper"></div>
  </div>
</template>

<script>
import WEditor from 'wangeditor'
import {uploadPhoto} from "@/api/image";

export default {
  name: 'WangEditor',
  props: {
    prefixCls: {
      type: String,
      default: 'ant-editor-wang'
    },
    // eslint-disable-next-line
    value: {
      type: String
    },
    disable: {
      type: Boolean,
      default:false
    }
  },
  data () {
    return {
      editor: null,
      editorContent: null
    }
  },
  watch: {
    value (val) {
      this.editorContent = val
      if(this.editor!=null) this.editor.txt.html(val)
    },
    disable(val){
      if(this.editor!=null){
        if(val){
          this.editor.txt.html(this.value)
          this.editor.disable()
        }else {
          this.editor.txt.html(this.value)
          this.editor.enable()
        }
      }
    }
  },
  mounted () {
    this.initEditor()
  },
  methods: {
    initEditor () {
      this.editor = new WEditor(this.$refs.editor)
      this.editor.config.customUploadImg =  (resultFiles, insertImgFn)=>{
        let form = new FormData();
        form.set('photo', resultFiles[0]);
        uploadPhoto(form).then((res)=>{
          insertImgFn(res.data)
        })
      }

      // this.editor.onchangeTimeout = 200
      this.editor.config.onchange = (html) => {
        this.editorContent = html
        this.$emit('change', this.editorContent)
      }
      this.editor.create()
      this.editorContent = this.value
      this.editor.txt.html(this.value)

      if(this.disable){
        this.editor.disable()
      }else {
        this.editor.enable()
      }
    }
  }
}
</script>

<style lang="less" scoped>
.ant-editor-wang {
  .editor-wrapper {
    text-align: left;
  }
}
</style>
